package cn.baiweigang.uu.task;

import cn.baiweigang.uu.BTContext;
import cn.baiweigang.uu.api.linearswap.MarketWs;
import cn.baiweigang.uu.api.linearswap.OrderNotificationWs;
import cn.baiweigang.uu.constants.BtcConfig;
import cn.baiweigang.uu.enums.ContractCodeEnum;
import cn.baiweigang.uu.model.AccountInfo;
import cn.baiweigang.uu.service.linearswap.AccountService;
import cn.baiweigang.uu.strategy.StrategyAction;
import cn.baiweigang.uu.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

@Component
public class TaskStart implements CommandLineRunner {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private AccountService accountService;
    @Autowired
    private MarketWs marketWs;
    @Autowired
    private OrderNotificationWs orderNotificationWs;

    @Override
    public void run(String... args) throws Exception {
        LogUtil.logInfo("程序启动 加载账号信息");
        AccountInfo accountInfo = accountService.queryFromDb(BtcConfig.ACCOUNT_NAME);
        if (accountInfo.getContractCode() == ContractCodeEnum.BTC_USDT) {
            loadLinearSwapAccount(accountInfo);
        } else if (accountInfo.getContractCode() == ContractCodeEnum.BTC_CQ) {
            loadFutureAccount(accountInfo);
        } else {
            LogUtil.logError("此账号无对应策略");
        }
    }

    /**
     * 交割合约
     *
     * @param accountInfo
     */
    private void loadFutureAccount(AccountInfo accountInfo) {
    }

    /**
     * USDT永续合约
     *
     * @param accountInfo
     */
    private void loadLinearSwapAccount(AccountInfo accountInfo) {
        try {
            StrategyAction min5Strategy = (StrategyAction) getBeanByClassName(accountInfo.getStrategyName());
            min5Strategy.setAccountInfo(accountInfo);
            if (min5Strategy.init()) {
                LogUtil.logInfo("账号：" + accountInfo.getAccountName() + " 加载成功，开始执行自动化交易");
                BTContext.StrategyCache.put(accountInfo.getAccountName(), min5Strategy);
            } else {
                LogUtil.logError("初始化策略失败 ");
                return;
            }
            //给账号 启动订单监听
            if (!orderNotificationWs.sub(accountInfo.getAccountName(), accountInfo.getContractCode())) {
                LogUtil.logError("启动订单监听异常");
            }
            //启动市场行情监听
            if (!marketWs.sub(accountInfo.getContractCode(), accountInfo.getPeriod())) {
                LogUtil.logError("启动行情监听异常");
            }
        } catch (Throwable e) {
            LogUtil.logError("加载账户信息异常 " + e.getMessage());
        }
    }

    private Object getBeanByClassName(String className) {
        className = className.substring(0, 1).toLowerCase() + className.substring(1);
        return applicationContext.getBean(className);
    }
}
